package com.ml.carManager.utils.map;

import java.math.BigDecimal;

public class DistanceUtils {
    private final static double PI = 3.14159265358979323; // 圆周率
    private final static double R = 6371229; // 地球的半径

    public static double getDistance(double lat1, double longt1, double lat2,
                                     double longt2) {
        double x, y, distance;
        x = (longt2 - longt1) * PI * R
                * Math.cos(((lat1 + lat2) / 2) * PI / 180) / 180;
        y = (lat2 - lat1) * PI * R / 180;
        distance = Math.hypot(x, y);
        return distance;
    }

    public static double getDistance(String lat1, String longt1, String lat2,
                                     String longt2) {
        double x = 0, y = 0, distance = 0, la1 = 0, ln1 = 0, la2 = 0, ln2 = 0;
        try {
            la1 = Double.parseDouble(lat1);
            ln1 = Double.parseDouble(longt1);
            la2 = Double.parseDouble(lat2);
            ln2 = Double.parseDouble(longt2);
        } catch (Exception e) {
            la1 = 0;
            ln1 = 0;
            la2 = 0;
            ln2 = 0;
        }

        x = (ln2 - ln1) * PI * R * Math.cos(((la1 + la1) / 2) * PI / 180) / 180;
        y = (la2 - la1) * PI * R / 180;
        distance = Math.hypot(x, y);
        return distance;
    }

    /**
     * 格式化距离单位为km
     */
    public static String getDistanceFormatRS(double distance) {
        int d = (int) distance;
        float res = (d / 1000f);
        BigDecimal b = new BigDecimal(res);
        res = (float) b.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
        return res + "";
    }

    /**
     * 格式化距离单位为km
     */
    public static float getDistanceFormatRF(double distance) {
        int d = (int) distance;
        float res = (d / 1000f);
        BigDecimal b = new BigDecimal(res);
        res = (float) b.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
        return res;
    }
}
